package com.sky.service.admin.impl;

import ch.qos.logback.classic.pattern.MessageConverter;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.exception.ParameterIsNullException;
import com.sky.mapper.admin.CategoryMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.pojo.Category;
import com.sky.pojo.Courier;
import com.sky.pojo.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.CategoryService;
import com.sky.vo.CategorySelectIdVO;
import com.sky.vo.DishSelectIdVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.KSQLJoinWindow;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CategoryServicelmpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Resource
    RedisTemplate redisTemplate;

    private static final Integer STATUS = 1;
    @Autowired
    private DishMapper dishMapper;


    @Override
    public Result<PageResult> selectPageCategory(CategoryPageQueryDTO dto) {
        if (dto.getPage() <= 0 || dto.getPageSize() <= 0) {
            throw new BaseException("参数非法");
        }
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Category> categories = categoryMapper.selectPageCategory(dto);
        PageResult build = PageResult.builder().records(categories.getResult()).total(categories.getTotal()).build();
        return Result.success(build);
    }

    @Override
    public void reviseCategory(CategoryDTO category) {
        Category category1 = new Category();
        BeanUtils.copyProperties(category, category1);

        categoryMapper.reviseCategory(category1);


        //给redis做准备
        Category cType = categoryMapper.selectById(category.getId());
        log.error("查到的数据{}", cType);
        //删除缓存
        // 清空缓存
        try {
            Boolean adminDelete = redisTemplate.delete(RedisConstant.CATEGORY_LIST + cType.getType());
            log.info("后端删除缓存:{}", adminDelete);
            Boolean userDelete = redisTemplate.delete(RedisConstant.USERCATEGORY_LIST);
            log.warn("小程序删除的缓存{}", userDelete);
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除缓存失败的远呀:{}",e.getMessage());
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertCategory(CategoryDTO category) {
        Category selectCategoryName = categoryMapper.selectByName(category.getName());
        if (Objects.nonNull(selectCategoryName)) {
            throw new BaseException("该分类已存在");
        }
        Category newCategory = new Category();
        BeanUtils.copyProperties(category, newCategory);
        newCategory.setStatus(STATUS);
        categoryMapper.insertCategory(newCategory);
        // 清空缓存
        try{
            Boolean adminDelete = redisTemplate.delete(RedisConstant.CATEGORY_LIST + newCategory.getType());
            log.info("后端删除缓存:{}", adminDelete);
            redisTemplate.delete(RedisConstant.USERCATEGORY_LIST);
            log.info("后端删除缓存:{}", adminDelete);
        }  catch (Exception e){
            e.printStackTrace();
            log.error("删除缓存失败的远呀:{}",e.getMessage());
        }
    }

    @Override
    public List<CategorySelectIdVO> selectTypeCategory(Integer type) {
        /**
         * 1.查询缓存,有就直接返回
         * 2.没有查询数据库,把查询到的数据放到数据库
         */
        //查询缓存 category:1
        List<CategorySelectIdVO> redisCategory = (List<CategorySelectIdVO>) redisTemplate.opsForValue().get(RedisConstant.CATEGORY_LIST + type);
        // 如果不为空就直接返回数据
        if (CollectionUtils.isNotEmpty(redisCategory)) {
            System.err.println("从缓存中查取数据");
            return redisCategory;
        }
        // 没有的话 就从数据中查询 再放到缓存中
        System.err.println("从mysql中查取数据");
        redisCategory = categoryMapper.selectTypeId(type);
        redisTemplate.opsForValue().set(RedisConstant.CATEGORY_LIST + type, redisCategory, 60 * 60, TimeUnit.SECONDS);
        return redisCategory;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteById(Integer id) {
        List<DishSelectIdVO> dishSelectIdVOS = dishMapper.selectId(id);
        log.info("查询出来的数据{}", dishSelectIdVOS);
        if (!dishSelectIdVOS.isEmpty()) {
            throw new ParameterIsNullException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }




        Category category = categoryMapper.selectById(Long.valueOf(id));
        int i = categoryMapper.deleteById(id);

        //删除缓存
        try {
            Boolean adminDelete = redisTemplate.delete(RedisConstant.CATEGORY_LIST + category.getType());
            log.info("后端删除缓存:{}", adminDelete);
            Boolean userDelete = redisTemplate.delete(RedisConstant.USERCATEGORY_LIST);
            log.info("后端删除缓存:{}", adminDelete);
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除缓存失败的远呀:{}",e.getMessage());
        }
        return i;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reviseStatus(Integer status, Long id) {
        Category category = Category.builder().id(id).status(status).build();

        categoryMapper.reviseStatus(category);
        Category cType = categoryMapper.selectById(id);


        //删除缓存
        try {
            Boolean adminDelete = redisTemplate.delete(RedisConstant.CATEGORY_LIST + cType.getType());
            log.info("后端删除缓存:{}", adminDelete);
            Boolean userDelete = redisTemplate.delete(RedisConstant.USERCATEGORY_LIST);
            log.info("后端删除缓存:{}", adminDelete);
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除缓存失败的远呀:{}",e.getMessage());
        }
    }
}
